package api

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"monitor_serve/meta"
	"monitor_serve/service"
	"net/http"
)

type FileMetaApi struct{}

func (f *FileMetaApi) GetFileMetaHandler(c *gin.Context) {
	// 从查询参数中获取filehash
	filehash := c.Query("filehash")

	// 调用GetFileMeta方法获取文件元数据
	//fMeta := meta.GetFileMeta(filehash)
	fMeta, err := service.ServiceGroupApp.FileService.GetFileMeta(filehash)
	if err != nil {
		fmt.Println(err)
	}

	// 将文件元数据序列化为JSON
	data, err := json.Marshal(fMeta)
	if err != nil {
		// 如果序列化失败，返回500 Internal Server Error
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal file meta"})
		return
	}

	// 写入响应数据
	c.Data(http.StatusOK, gin.MIMEJSON, data)
}

// 更新元信息接口（重命名）
func (f *FileMetaApi) FileMetaUpdateHandler(c *gin.Context) {
	// 从请求体中获取opType、fileSha1和newFileName
	var req struct {
		OpType   string `form:"op"`
		FileHash string `form:"filehash"`
		FileName string `form:"filename"`
	}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}

	opType := req.OpType
	fileSha1 := req.FileHash
	newFileName := req.FileName

	if opType != "0" {
		c.JSON(http.StatusForbidden, gin.H{"error": "Operation not allowed"})
		return
	}
	if c.Request.Method != "POST" {
		c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Method not allowed"})
		return
	}

	curFileMeta := meta.GetFileMeta(fileSha1)
	curFileMeta.FileName = newFileName
	meta.UpdateFileMeta(curFileMeta)

	data, err := json.Marshal(curFileMeta)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal file meta"})
		return
	}
	c.Data(http.StatusOK, gin.MIMEJSON, data)
}
